<template>
  <a-comment>
    <template #avatar>
      <a-avatar :src="loginUserStore.loginUser.userAvatar" alt="用户头像" />
    </template>
    <template #content>
      <a-card>
        <!-- 评论输入框 -->
        <a-textarea
          v-model:value="commentContent"
          :rows="2"
          style="background-color: #f5f5f5; margin-bottom: 8px; width: 100%; height: 50px"
          maxLength="720"
          placeholder="快和大家讨论吧~"
        />
        <a-row justify="end">
          <a-col>
            <a-button type="primary" @click="submitComment">发布</a-button>
          </a-col>
        </a-row>

        <!-- 评论列表 -->
        <a-list
          class="comment-list"
          :header="`${CommentList.length} 条评论`"
          item-layout="horizontal"
          :data-source="CommentList"
        >
          <template #renderItem="{ item }">
            <a-list-item>
              <CommentItem :comment-data="item" @on-reply-submit="handleReplySubmit" />
            </a-list-item>
          </template>
        </a-list>
      </a-card>
    </template>
  </a-comment>
</template>

<script lang="ts" setup>
import { addCommentUsingPost, listCommentVoByPageUsingPost } from '@/api/commentController'
import { useLoginUserStore } from '@/stores/user'
import dayjs from 'dayjs'
import relativeTime from 'dayjs/plugin/relativeTime'
import { onMounted, reactive, ref } from 'vue'
import CommentItem from './CommentItem.vue'

// 引入响应式变量存储评论内容
const commentContent = ref('')
const loginUserStore = useLoginUserStore()

dayjs.extend(relativeTime)
const CommentList = reactive<API.CommentVO[]>([])

const commentQueryParams = reactive<API.CommentQueryRequest>({
  current: 1,
  pageSize: 10,
})

// 获取评论列表数据
const getCommentsListData = async () => {
  try {
    const res = await listCommentVoByPageUsingPost(commentQueryParams)
    console.log('评论数据', res)

    // 处理每条评论的时间和回复相关属性
    res.data.data.records.forEach((item: any) => {
      item.dayjsCreateTime = dayjs(item.create_time)
      item.showReplyInput = false // 控制回复输入框显示
      item.replyContent = '' // 回复内容
      item.targetReplyId = null // 目标回复ID

      // 处理子评论
      if (item.children && item.children.length > 0) {
        item.children.forEach((child: any) => {
          child.showReplyInput = false
          child.replyContent = ''
        })
      }
    })

    CommentList.length = 0
    CommentList.push(...res.data.data.records)
    console.log('评论列表查询成功', CommentList)
  } catch (error) {
    console.error('评论列表查询失败', error)
  }
}

// 提交评论
const submitComment = async () => {
  if (!commentContent.value.trim()) {
    return
  }

  try {
    // 这里需要根据实际接口调整参数
    const params = {
      content: commentContent.value,
      topic_id: '1', // 假设的主题ID，实际应从父组件传入
      topic_type: '图书',
      parent_id: null,
      root_id: null,
    }

    await addCommentUsingPost(params)
    // 提交成功后重新获取评论列表
    commentContent.value = ''
    getCommentsListData()
  } catch (error) {
    console.error('发布评论失败', error)
  }
}
// 提交回复
const handleReplySubmit = async (targetItem: any) => {
  if (!targetItem.replyContent.trim()) return

  try {
    const params = {
      content: targetItem.replyContent,
      topic_id: '1',
      topic_type: '图书',
      parent_id: targetItem.id, // 回复的父级评论ID
      root_id: targetItem.root_id || targetItem.id, // 根评论ID
    }

    await addCommentUsingPost(params)
    // 提交成功后重新获取评论列表
    getCommentsListData()
  } catch (error) {
    console.error('发布回复失败', error)
  }
}

onMounted(() => {
  getCommentsListData()
})
</script>

<style scoped>
.comment-content {
  position: relative;
}

.comment-meta {
  margin-top: 8px;
  font-size: 12px;
  color: #888;
  display: flex;
  gap: 16px;
}

.comment-action {
  cursor: pointer;
  transition: color 0.2s;
}

.comment-action:hover {
  color: #1890ff;
}

.reply-input-container {
  margin-top: 8px;
  padding-left: 40px;
}

.reply-actions {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
}

.reply-list {
  margin-top: 12px;
  padding-left: 40px;
  border-left: 2px solid #eee;
}

.reply-to {
  color: #1890ff;
}

.reply-meta {
  margin-top: 4px;
  font-size: 12px;
  color: #888;
  display: flex;
  gap: 16px;
}

.reply-action {
  cursor: pointer;
  transition: color 0.2s;
}

.reply-action:hover {
  color: #1890ff;
}
</style>
